<template>
  <div class="expiring-students">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <div class="batch-actions" v-if="selectedStudents.length">
            <el-button type="primary" @click="handleBatchActivate">
              批量激活
            </el-button>
            <span class="selected-count">已选择 {{ selectedStudents.length }} 个学生</span>
          </div>
          <span v-else>到期学生</span>
          
          <el-radio-group v-model="timeRange" size="small">
            <el-radio-button label="7">7天内</el-radio-button>
            <el-radio-button label="30">30天内</el-radio-button>
            <el-radio-button label="90">90天内</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      
      <search-bar @search="handleSearch" />
      
      <data-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        :columns="columns"
        @selection-change="handleSelectionChange"
      >
        <template #actions="{ row }">
          <el-button 
            link 
            type="primary" 
            @click="handleTableAction({ action: 'activate', row })"
          >
            激活
          </el-button>
          <el-button 
            link 
            type="danger" 
            @click="handleTableAction({ action: 'delete', row })"
          >
            删除
          </el-button>
        </template>
      </data-table>
    </el-card>

    <activate-dialog
      ref="activateDialogRef"
      @confirm="handleActivateConfirm"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { studentService } from '../../services/student'
import DataTable from '../../components/common/DataTable.vue'
import { showSuccess, showError, showWarning } from '../../utils/message'
import { ElMessageBox } from 'element-plus'
import ActivateDialog from '../../components/studentlist/ActivateDialog.vue'
import { useStudentStore } from '../../stores/student'
import SearchBar from '../../components/studentlist/SearchBar.vue'

const studentStore = useStudentStore()
const activateDialogRef = ref(null)

// 表格数据
const loading = ref(false)
const tableData = ref([])

// 选择时间范围
const timeRange = ref('30')

// 表格列配置
const columns = [
  { type: 'index', label: '序号', width: '60', align: 'center' },
  { prop: 'account', label: '账号', align: 'center' },
  { prop: 'name', label: '姓名', width: '100', align: 'center' },
  { prop: 'phone', label: '手机号', width: '120', align: 'center' },
  { prop: 'school', label: '学校', width: '120', align: 'center' },
  { prop: 'class', label: '班级', align: 'center' },
  { prop: 'teacher', label: '老师', width: '100', align: 'center' },
  { 
    prop: 'expireTime', 
    label: '到期时间', 
    width: '180', 
    align: 'center',
    renderCell: ({ row }) => {
      const remainingDays = row.remainingDays
      let type = ''
      if (remainingDays <= 0) {
        type = 'danger'
      } else if (remainingDays <= 1) {
        type = 'error'
      } else if (remainingDays <= 7) {
        type = 'warning'
      }
      return h('div', { style: 'display: flex; align-items: center; gap: 8px;' }, [
        h('span', {}, row.expireTime),
        type && h(ElTag, { 
          type, 
          effect: 'light',
          size: 'small'
        }, () => remainingDays <= 0 ? '已过期' : `剩${remainingDays}天`)
      ])
    }
  },
  {
    slot: 'actions',
    label: '操作',
    width: '180',
    align: 'center',
    fixed: 'right'
  }
]

// 加载即将到期的学生数据
const loadExpiringStudents = async () => {
  try {
    loading.value = true
    const { data } = await studentService.getExpiringStudents(Number(timeRange.value))
    tableData.value = data
  } catch (error) {
    showError('加载数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 处理表格操作
const handleTableAction = async ({ action, row }) => {
  try {
    switch (action) {
      case 'delete':
        try {
          await ElMessageBox.confirm(
            `确定要删除学生 ${row.name}(${row.account}) 的账号信息吗？`,
            '删除确认',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
          await studentService.deleteStudents([row.id])
          showSuccess('删除成功')
          await loadExpiringStudents()
        } catch (err) {
          if (err !== 'cancel') throw err
        }
        break
      case 'activate':
        studentStore.setSelectedStudents([row])
        activateDialogRef.value?.openDialog()
        break
    }
  } catch (error) {
    showError('操作失败')
    console.error(error)
  }
}

// 处理激活确认
const handleActivateConfirm = async (formData) => {
  try {
    await studentService.activateStudents(
      studentStore.selectedStudents.map(item => item.id),
      formData.activeDays
    )
    showSuccess('激活成功')
    studentStore.clearSelection()
    await loadExpiringStudents()
  } catch (error) {
    showError('激活失败')
    console.error(error)
  }
}

// 添加搜索处理
const handleSearch = async (params) => {
  try {
    loading.value = true
    const { data } = await studentService.getExpiringStudents(Number(timeRange.value), params)
    tableData.value = data
  } catch (error) {
    showError('加载数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 监听时间范围变化
watch(() => timeRange.value, () => {
  loadExpiringStudents()
})

onMounted(() => {
  loadExpiringStudents()
})

// 添加选择相关逻辑
const selectedStudents = ref([])

const handleSelectionChange = (selection) => {
  selectedStudents.value = selection
  studentStore.setSelectedStudents(selection)
}

// 添加批量操作按钮处理
const handleBatchActivate = () => {
  if (!selectedStudents.value.length) {
    showWarning('请选择要激活的学生')
    return
  }
  activateDialogRef.value?.openDialog()
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.student-table {
  margin-top: 20px;
}

.batch-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.selected-count {
  color: var(--el-text-color-secondary);
  font-size: 14px;
}
</style>
